//
//  LoginViewController.m
//  oschina_song
//
//  Created by song on 16/2/16.
//  Copyright © 2016年 song. All rights reserved.
//

#import "LoginViewController.h"
#import "OSCAPI.h"
#import "Ono.h"
#import "AFHTTPRequestOperationManager+Util.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "Utils.h"
#import "OSCUser.h"
#import "OSCThread.h"

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *accountField;

@property (weak, nonatomic) IBOutlet UITextField *passwdField;

@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation LoginViewController


-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    
    if(self)
    {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    self.hidesBottomBarWhenPushed = YES;
    
}

/**
 <result>
 <errorCode>1</errorCode>
 <errorMessage><![CDATA[登录成功]]></errorMessage>
 </result>
 
**/


- (IBAction)loginClick:(id)sender {
    
    
    _hud =[Utils createHUD];
    _hud.labelText =@"正在登录";
    _hud.userInteractionEnabled =NO;
    NSString *loginurl= [NSString stringWithFormat:@"%@%@",OSCAPI_HTTPS_PREFIX,OSCAPI_LOGIN_VALIDATE];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager OSCManger];
    [manger POST:loginurl parameters:@{@"username":_accountField.text ,@"pwd":_passwdField.text,@"keep_login":@(1)}
         success:^(AFHTTPRequestOperation * _Nonnull operation, ONOXMLDocument *responseObject) {
             ONOXMLElement *result = [responseObject.rootElement firstChildWithTag:@"result"];
             NSInteger errorCode  =[[[result firstChildWithTag:@"errorCode"] numberValue] intValue];
             if(!errorCode)
             {
                 
             }
             
             [Config saveOwnAccount:_accountField.text andPasswd:_passwdField.text];
             ONOXMLElement *userXML = [responseObject.rootElement firstChildWithTag:@"user"];
             [self renewUserWithXML:userXML];
             
         } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
          
         }];
    
    
}


-(void)renewUserWithXML:(ONOXMLElement *)xml
{
    [Config saveProfile:[[OSCUser alloc] initWithXML:xml]];
    
    [OSCThread startPollingNotice];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
